import {request} from "./request";

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }

  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date

  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }

    date = new Date(time)
  }

  // Set the time zone to Shanghai (UTC+8)
  const options = { timeZone: 'Asia/Shanghai', hour12: false }
  const formatObj = {
    y: date.toLocaleString('en-US', { ...options, year: 'numeric' }),
    m: date.toLocaleString('en-US', { ...options, month: '2-digit' }),
    d: date.toLocaleString('en-US', { ...options, day: '2-digit' }),
    h: date.toLocaleString('en-US', { ...options, hour: '2-digit' }),
    i: date.toLocaleString('en-US', { ...options, minute: '2-digit' }),
    s: date.toLocaleString('en-US', { ...options, second: '2-digit' }),
    a: date.toLocaleString('en-US', { ...options, weekday: 'short' }),
  }

  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][new Date(time).getDay()]
    }
    return value.toString().padStart(2, '0')
  })

  return time_str
}


export default request
